<template>

    <ayjDialog ref="ayjDialogRef" :width="'30%'" :fullscreen="false" :title="'开机次数'" :slotFooter="false">
        <div class="dialog-content">
            <div class="dialog-content-header">
                <el-steps :active="activeNum" simple process-status="wait">
                    <el-step title="选择仪器设备" icon="el-icon-info"></el-step>
                    <el-step title="设置次数" icon="el-icon-edit "></el-step>
                </el-steps>
            </div>
            <div class="dialog-content-body">
                <template v-if="activeNum == 1">
                    <div class="mr5">
                        <template v-if="listData && listData.length > 0">
                            <div :class="['list-cell', 'flex_between', currDev.type_dev == item.type_dev ? 'active' : '']"
                                v-for="(item, index) in listData" :key="index" @click="chooseDev(item)">
                                <div>
                                    <h3 class="font_black2">{{ item.type_name || '--' }}</h3>
                                    <h5>型号： {{ item.type_code || '--' }}</h5>
                                </div>
                                <div> 剩 <span class="font_red font_size20 ml5 mr5">{{ item.times || 0 }}</span> 次</div>
                                <img v-if="currDev.type_dev == item.type_dev" class="selete_img"
                                    src="static/icon/select.svg" alt="">
                            </div>
                        </template>
                        <empty v-else-if="listData && listData.length == 0" />
                        <div class="flex_center" v-if="listData && listData.length > 0">
                            <div class="mt10 mb20"> 暂无更多数据~ </div>
                        </div>
                    </div>
                </template>
                <template v-if="activeNum == 2">
                    <div>
                        <h4>型号：{{ currDev.type_name }} {{ currDev.type_code }} </h4>
                        <div class="flex_between">
                            <div>
                                <i class="el-icon-s-data" style="color: #4fa5ff;font-size: 16px;"></i>
                                <span class="ml5">本店可用次数：<span class="bold font_size20 font_yellow"
                                        style="margin-right: 3px;">{{ infoDevsetTime.times || 0 }}</span> 次 </span>
                            </div>
                            <div>
                                <span class="under-line font_bule" @click="openDevLog"> 本店流水 </span>
                            </div>
                        </div>
                        <div class="info-box" v-if="Number(infoDevsetTime.times) < 50">
                            <div>
                                <i class="el-icon-info" style="color: #909399;font-size: 18px;"></i>
                                <span class="ml5"> 提示：本店可用次数不多，请先联系{{ touch_us.who_txt || '平台客服' }}。</span>
                            </div>
                            <p style="margin-left: 24px;">
                                <span>电话：{{ touch_us.phone || '--' }}</span>
                                <span class="ml20">微信：{{ touch_us.wx || '--' }}</span>
                            </p>
                        </div>
                    </div>
                    <el-divider></el-divider>
                    <h4 class="mb5 flex_between">
                        <span>客户：{{ customerRow.name + ' ' }}</span>
                        <span class="font_bule under-line" style="font-weight: normal;" @click="openTaLog"> Ta的流水
                        </span>
                    </h4>
                    <div class="info-waring-box flex_row">
                        <i class="el-icon-warning-outline" style="color: #e6a23c;font-size: 24px;"></i>
                        <div class="ml10 flex1">
                            <span class="font_size16"> {{ '剩余次数：' + currDev.times + ' ' + '次' }} </span>
                        </div>
                    </div>
                    <div class="content mt10">
                        <el-form ref="formRef" :model="objectForm" :rules="rules" label-width="90px">
                            <el-form-item label="充值类型:" prop="in_out">
                                <el-radio v-model="objectForm.in_out" label="1">转次数给Ta</el-radio>
                                <el-radio v-model="objectForm.in_out" label="2">收回次数</el-radio>
                            </el-form-item>
                            <el-form-item label="次数:" prop="times">
                                <el-input type="number" v-model="objectForm.times" placeholder="请输入次数"
                                    style="width: 300px;font-size: 16px;"></el-input>
                            </el-form-item>
                            <el-form-item label="备注:" class="mt20" prop="txt">
                                <el-input type="textarea" v-model="objectForm.txt" placeholder="请输入备注"
                                    style="width: 300px;"></el-input>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
            </div>
            <div class="flex_center dialog-content-footer">
                <div v-if="activeNum == 1">
                    <!-- <el-button style="width: 200px;" type="primary" @click="nextHandle" size="small" :disabled="!currDev.type_dev"> 下一步
                    </el-button> -->
                </div>
                <div v-else>
                    <el-button @click="prevtHandle" size="small" style="width: 150px;"> 上一步 </el-button>
                    <el-button type="primary" @click="btnHandle" size="small" style="width: 150px;"> 确定 </el-button>
                </div>
            </div>
        </div>
        <devDialogLog ref="devDialogLogRef" :who="whoType" :title="titleName" :customerRow="customerRow"></devDialogLog>
    </ayjDialog>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch, onUnmounted, computed, onBeforeUnmount, defineProps, defineExpose, nextTick } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import devDialogLog from '@/pages/device/components/devDialogLog.vue'

// 获取当前组件实例
const { proxy } = getCurrentInstance()

const props = defineProps({
    customerRow: {
        type: Object,
        default: () => { }
    }
})

// 设备列表
const query = ref({
    who: 'u',  // 读取谁的次数：cp=企业自己的；u=客户的
    uid: '', // 客户uid，who=cp时无须传值；
})

// 次数
const queryBillLs = ref({
    who: 'u',  // 读取谁的次数：cp=企业自己的；u=客户的
    uid: '', // 客户uid，who=cp时无须传值；
    in_out: '', // 1=充值 2=消耗   不传 or 其他 默认1
    pfrom: 0,
    pnum: 20,
})

const objectForm = ref({
    in_out: '1', // 方向：1增，2减
    times: '',
    txt: '',
    uid: '', // 客户id,
    type_dev: '', // 设备类型
})

// 新增：表单校验规则
const rules = ref({
    in_out: [
        { required: true, message: '请输入次数', trigger: 'blur' }
    ],
    times: [
        { required: true, message: '请输入次数', trigger: 'blur' }
    ],
    txt: [
        { required: false, message: '请输入备注', trigger: 'blur' }
    ]
})

// 读取谁的流水  who ：cp=企业自己的；u=客户的
// 本地流水
const devDialogLogRef = ref(null)
const whoType = ref(null)
const titleName = ref('')
const openDevLog = () => {
    whoType.value = 'cp'
    titleName.value = '本店流水'
    devDialogLogRef.value.open()
}

// 客户流水 
const openTaLog = () => {
    whoType.value = 'u'
    titleName.value = props.customerRow.name + '【' + currDev.value.type_name + '】' + '的流水'
    devDialogLogRef.value.open()
}

const currDev = ref({})
const chooseDev = (item) => {
    activeNum.value = 2
    currDev.value = item
    getDevsetTime()
}

const touch_us = ref({})
const loading = ref(false)
const listData = ref([])

// 查询设备列表
const getDevsetList = async () => {
    try {
        let param = {
            ...query.value,
            uid: props.customerRow.uid
        }
        loading.value = true
        let res = await proxy.$api({ url: config.devtimes_get_ls, data: param });
        if (res.status == 1) {
            let list = res?.data?.ls || []
            if (list && list.length > 0) {
                listData.value = listData.value.concat(list || [])
            }
            touch_us.value = res?.data?.touch_us
        }
        loading.value = false
    } catch (error) {
        loading.value = false
        // proxy.$message({
        //     message: '操作失败',
        //     type: 'error'
        // });
    }
}

// 查询门店剩余次数
const infoDevsetTime = ref({})
const getDevsetTime = async () => {
    try {
        let param = {
            who: 'cp',
            type_dev: currDev.value.type_dev
        }
        let res = await proxy.$api({ url: config.devtimes_get_ls, data: param });
        if (res.status == 1) {
            infoDevsetTime.value = res?.data?.info
        }
    } catch (error) { }
}

// 查询次数
const getDevtimesBillLs = async () => {
    try {
        let param = {
            ...queryBillLs.value,
            uid: props.customerRow.uid
        }
        console.log("param==", param)
        loading.value = true
        let res = await proxy.$api({ url: config.devtimes_bill_ls, data: param });
        if (res.status == 1) {
            let list = res?.data?.ls || []
            if (list && list.length > 0) {
                listData.value = listData.value.concat(list || [])
            }
            touch_us.value = res?.data?.touch_us
        }
        loading.value = false
    } catch (error) {
        loading.value = false
        // proxy.$message({
        //     message: '操作失败',
        //     type: 'error'
        // });
    }
}

const formRef = ref(null)
const btnHandle = async () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        let param = {
            ...objectForm.value,
            uid: props.customerRow.uid,
            type_dev: currDev.value.type_dev
        }
        if (param.in_out == 1 && param.times > infoDevsetTime.value.times) {
            proxy.$message({
                message: '给旗下企业充值的次数不能大于您同型号设备的剩余次数，请先向平台客服申请充值',
                type: 'error'
            });
            return
        }
        if (param.in_out == 2 && param.times > currDev.value.times) {
            proxy.$message({
                message: '剩余次数不够减',
                type: 'error'
            });
            return
        }
        let res = await proxy.$api({ url: config.devtimes_save, data: param });
        if (res.status == 1) {
            proxy.$message({
                message: '操作成功',
                type: 'success'
            })
            ayjDialogRef.value.close()
        }
    });
}

const activeNum = ref(1)
const nextHandle = () => {
    activeNum.value = 2
}

const prevtHandle = () => {
    activeNum.value = 1
    objectForm.value = {
        in_out: '1', // 方向：1增，2减
        times: '',
        txt: '',
        uid: '', // 客户id,
        type_dev: '', // 设备类型
    }
}

const ayjDialogRef = ref(null)
const open = () => {
    ayjDialogRef.value.open()
    nextTick(() => {
        resetForm()
        getDevsetList()
    })
}

const resetForm = () => {
    activeNum.value = 1
    listData.value = []
    currDev.value = {}
    objectForm.value = {
        in_out: '1', // 方向：1增，2减
        times: '',
        txt: '',
        uid: '', // 客户id,
        type_dev: '', // 设备类型
    }
    // formRef.value.resetFields()
    // formRef.value.clearValidate()
}

const close = () => {
    ayjDialogRef.value.close()
}

onMounted(() => { })
onBeforeUnmount(() => { })
onUnmounted(() => { })

defineExpose({
    open,
    close
})

</script>

<style lang="scss" scoped>
.dialog-content {
    display: flex;
    flex-direction: column;
    height: 550px;

    &-header {
        margin-bottom: 10px;
    }

    &-body {
        flex: 1 1 auto;
        overflow: auto;
    }

    &-footer {
        margin: 14px 0 0 0;
    }
}

.list-cell {
    border-radius: 8px;
    padding: 10px;
    background-color: #f5f7fa;
    margin-bottom: 10px;
    border: 1px solid #f5f7fa;
    position: relative;
    overflow: hidden;
    transition: all 0.2s ease-in-out;

    .selete_img {
        position: absolute;
        top: 0;
        right: 0;
        height: 20px;
        width: 20px;
    }
}

.list-cell:hover {
    background-color: rgba(108, 159, 241, 0.2);
}

.active {
    background-color: rgba(108, 159, 241, 0.2);
}

::v-deep .el-divider {
    margin: 10px 0 !important;
}

.info-box {
    padding: 10px 14px;
    background-color: #f4f4f5;
    color: #909399;
    border-radius: 6px;
}

.info-waring-box {
    padding: 10px 14px;
    background-color: #fdf6ec;
    color: #eaae55;
    border-radius: 6px;
}
</style>